package main

import (
	_ "github.com/go-sql-driver/mysql"

	"database/sql"
	"fmt"
	"sync"
)

func main() {
	dbLink := "root:root@tcp(localhost:3307)/productions_payment"

	db, err := sql.Open("mysql", dbLink)
	if err != nil {
		panic(err)
	}
	defer func(db *sql.DB) {
		err := db.Close()
		if err != nil {
			panic(err)
		}
	}(db)

	database := NewDatabase(db)

	go database.Read()

	database.Write(1)

	result := <-database.result
	fmt.Println("读取到的结果:", result)
}

func NewDatabase(db *sql.DB) *Database {
	return &Database{
		db:     db,
		wg:     sync.WaitGroup{},
		result: make(chan int),
	}
}

type Database struct {
	mu     sync.Mutex
	db     *sql.DB
	wg     sync.WaitGroup
	result chan int
}

func (d *Database) Read() {
	d.wg.Add(1)

	go func() {
		defer d.wg.Done()

		rows, err := d.db.Query("SELECT COUNT(*) FROM test_counter")
		if err != nil {
			panic(err)
		}
		defer func(rows *sql.Rows) {
			err := rows.Close()
			if err != nil {
				panic(err)
			}
		}(rows)

		var count int
		for rows.Next() {
			err := rows.Scan(&count)
			if err != nil {
				panic(err)
			}
			d.result <- count
		}
	}()
}
func (d *Database) Write(id int) {
	d.wg.Add(1)

	go func() {
		defer d.wg.Done()

		_, err := d.db.Exec("INSERT INTO test_counter (id, count) VALUES (?, 1)", id)
		if err != nil {
			panic(err)
		}
	}()
}
func (d *Database) Wait() {
	d.wg.Wait()
	close(d.result)

	for result := range d.result {
		fmt.Println("Final count:", result)
	}
}
func (d *Database) ReadRecord(id int) (int, error) {
	d.mu.Lock()
	defer d.mu.Unlock()

	rows, err := d.db.Query("SELECT id, value FROM my_table WHERE id = ?", id)
	if err != nil {
		panic(err)
	}
	defer func(rows *sql.Rows) {
		err := rows.Close()
		if err != nil {
			panic(err)
		}
	}(rows)

	var recordID, recordValue int
	for rows.Next() {
		err := rows.Scan(&recordID, &recordValue)
		if err != nil {
			panic(err)
		}
		return recordValue, nil
	}

	return 0, nil
}
func (d *Database) WriteRecord(id int, value int) {
	d.mu.Lock()
	defer d.mu.Unlock()

	_, err := d.db.Exec("UPDATE my_table SET value = ? WHERE id = ?", value, id)
	if err != nil {
		panic(err)
	}
}
